﻿using System;
using System.Web.Configuration;
using System.Web.Mvc;
using ML.Entity;
using ML.IBusiness;
using ML.Plug;
using ML.Utils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;

namespace ML.WebApi.Controllers
{
    /// <summary>
    /// 微信授权
    /// </summary>
    public class WeiXinAuthorizationController : Controller
    {
        private static readonly string AppId = WebConfigurationManager.AppSettings["TenPayV3_AppId"];
        private static readonly string WechatRedirect = WebConfigurationManager.AppSettings["WechatRedirect"];
        private static readonly string WechatHome = WebConfigurationManager.AppSettings["wechathome"];
        private readonly IUserBusiness userBusiness;
        private static readonly NLogLogger log = new NLogLogger();

        public WeiXinAuthorizationController(IUserBusiness userBusiness)
        {
            this.userBusiness = userBusiness;
        }

        [HttpGet]
        public ActionResult Index(string code = "", string state = "", string invitationCode = "")
        {
            if (!string.IsNullOrEmpty(code))
            {
                //根据传递的Code读取用户信息并且完成所有业务
                JObject userinfo = WechatHelper.OAuth2UserInfo(code);
                UserEntity userEntity = new UserEntity
                {
                    NickName = userinfo["nickname"].ToString(),
                    OpenId = userinfo["openid"].ToString(),
                    PhotoGraph = userinfo["headimgurl"].ToString(),
                    Gender = Convert.ToInt32(userinfo["sex"].ToString()),
                    Country = userinfo["country"].ToString(),
                    City = userinfo["city"].ToString(),
                    Province = userinfo["province"].ToString()
                };

                //处理业务并且返回(如果存在不插入否则插入)
                var data = userBusiness.AddWXUser(userEntity);
                log.Debug($"weixin is authorization success。{JsonConvert.SerializeObject(data)}");

                return Redirect($"{WechatHome}?userid={data.data.Id}");
            }
            if (string.IsNullOrEmpty(state))
            {
                state = "xlwm-xluo";
            }

            var userinfoAuthorizeUrl = OAuthApi.GetAuthorizeUrl(AppId, WechatRedirect, state,
                OAuthScope.snsapi_userinfo);
            return Redirect(userinfoAuthorizeUrl);
        }
    }
}